<?php

namespace app\admin\service;

use app\admin\model\Admin;
use app\lib\exception\TokenException;
use app\admin\model\Token as model;

class Token
{
    /**
     * 登录-生成token
     * @param $user_id
     * @param $key
     * @return false|string
     * @throws TokenException
     */
    static function createToken($user_id, $key)
    {
        if (!$user_id) {
            return false;
        }
        $where = [];
        $where[] = ['user_id', '=', $user_id];
        $where[] = ['type', '=', $key];
        $admin = (new model)->where($where)->findOrEmpty();
        if ($admin->isEmpty()) {
            //生成token
            $token = self::generateToken();
            //更新当前用户token 和 有效期
            $update = [
                'token' => $token,
                'update_time' => date('Y-m-d H:i:s'),
            ];

            $res = (new model)->where($where)->update($update);
        } else {
            //生成token
            $token = self::generateToken();
            //添加token
            $update = [
                'token' => $token,
                'create_time' => date('Y-m-d H:i:s'),
                'update_time' => date('Y-m-d H:i:s'),
                'type' => $key
            ];

            $res = (new model)->where($where)->save($update);
        }

        if ($res !== false) {
            return $token;
        } else {
            throw new TokenException();
        }
    }

    /**
     * 验证token
     * @throws TokenException
     */
    public static function checkPrimaryScope($token, $key): array
    {
        if (empty($token) && empty($key)) {
            throw new TokenException(['msg' => '参数缺失']);
        }
        $stars = (new model)->field('user_id,token,update_time')->where(['token' => $token, 'type' => $key])->findOrEmpty()->toArray();
        if (empty($stars)) throw new TokenException();
        $user = (new Admin)->where('id=' . $stars['user_id'])->findOrEmpty()->toArray();
        if ($user['status'] != 1) throw new TokenException(['msg' => '当前账户已被禁用']);
        return $stars;
    }

    /**
     * 刷新用户令牌
     * @param $user_id
     * @return string|null
     */
    public static function refreshUserToken(int $user_id, $key)
    {
        if (!$user_id) {
            return false;
        }

        //生成token
        $token = self::generateToken();

        //更新当前用户token 和 有效期
        $update = [
            'token' => $token,
            'update_time' => date('Y-m-d H:i:s'),
        ];
        $where = [];
        $where[] = ['user_id', '=', $user_id];
        $where[] = ['type', '=', $key];
        $res = (new model)->where($where)->update($update);
        if ($res !== false) {
            return true;
        } else {
            throw new TokenException();
        }
    }


    /**
     * 生成token
     * @return string
     */
    public static function generateToken()
    {
        $randeChar = getRandChar(32);
        $timestamp = $_SERVER['REQUEST_TIME_FLOAT'];
        $tokenSalt = config('secure.token_salt');
        return md5($randeChar . $timestamp . $tokenSalt);
    }
}